#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <SDL/SDL.h>

#include "zombies.h"
#include "victims.h"
#include "level.h"
#include "display.h"
#include "font.h"

// victims
victim_t victims[MAX_VICTIMS];

// sprites surface
SDL_Surface *victimsprites;

// victims names, aligned to sprites
struct names_t
{
    int code;
    const char *name;
}victimname[]=
{
    { 0x839D00, "Pool guy"    },
    { 0x839EBE, "Cheerleader" },
    { 0x839C6D, "Teacher"     },
    { 0x839776, "Baby"        },
    { 0x839A89, "Dog"         },
    { 0x839699, "Barbecue"    },
    { 0x839FE2, "Tourists"    },
    { 0x83993D, "Army"        },
    { 0x839843, "Trampoline"  },
    { 0x839E15, "Explorer"    },
    { 0x839BAD, "Dr. Bug"     }  // interesting code :-)
};

const char *getvictimname(int code)
{
    int i;
    for(i=0;i<=MAX_VICTIMS;i++)
        if(code==victimname[i].code)
            return victimname[i].name;
   
    return "ERROR";
}

int getvictimoffset(int code)
{
    int i;
    for(i=0;i<=MAX_VICTIMS;i++)
        if(code==victimname[i].code)
            return i;
    
    return 0;
}

int victimclicked(int x, int y)
{
    int i;
    for(i=0;i<MAX_VICTIMS;i++)
    {
        if(x>victims[i].x-32 && x<(victims[i].x+32) && y>victims[i].y-32 && y<(victims[i].y+16))
        {
            return i;
        }
    }

    return -1;
}

void dragvictim(int id, int x, int y)
{
    victims[id].x+=x;
    victims[id].y+=y;
}

// victims have fixed size at the rom.
void readvictims()
{
    unsigned int offset;

    offset=BASE_PTR+level.victim_ptr;
    memset(&victims,0,sizeof(victim_t)*MAX_VICTIMS);
    memcpy(&victims,romdata+offset,sizeof(victim_t)*MAX_VICTIMS);
}

void drawvictims()
{
    SDL_Rect src,dst;
    char buf[32];
    int i,tx,ty;

    // victims layer sizes
    src.w=dst.w=48;
    src.h=dst.h=48;
   
    for(i=0;i<MAX_VICTIMS;i++)
    {
		src.x=48*getvictimoffset(victims[i].code);
		src.y=0;
        
        // align to layer size
        dst.x=victims[i].x-bgoffset.x-32;
        dst.y=victims[i].y-bgoffset.y-48;
        
        // let SDL handle clipping
        SDL_BlitSurface(victimsprites,&src,screen,&dst);

        // center align text on sprite bottom
        snprintf(buf,sizeof(buf),"%d - %s",i+1,getvictimname(victims[i].code));
        tx=victims[i].x-bgoffset.x-(strlen(buf)*3);
        ty=victims[i].y-bgoffset.y;

        drawtext(buf,tx,ty);
    }
}

void initvictims()
{
    SDL_Surface *temp;
    
    temp=SDL_LoadBMP("victims.bmp");
    victimsprites=SDL_ConvertSurface(temp,screen->format,SDL_SWSURFACE);
    SDL_FreeSurface(temp);

    // apply color mask
    SDL_SetColorKey(victimsprites,SDL_SRCCOLORKEY,0xff00ff);
}